package com.sumer.psychology.photo.infrastructure.messaging.rabbitmq;

import com.sumer.psychology.comment.application.command.CommentApplicationService;
import com.sumer.psychology.comment.application.command.DeleteCommentsCommand;
import com.sumer.psychology.common.notification.NotificationReader;
import com.sumer.psychology.common.port.adapter.messaging.Exchanges;
import com.sumer.psychology.common.port.adapter.messaging.rabbitmq.ExchangeListener;
import com.sumer.psychology.photo.infrastructure.persistence.mongo.MongoAlbumRepository;
import com.sumer.psychology.photo.infrastructure.persistence.mongo.MongoPhotoRepository;
import org.apache.commons.lang3.StringUtils;

/**
 * 照片删除监听
 * <p/>
 * User: zhenguang.zhu
 * Date: 2014/10/29
 * Time: 14:04
 */
public class PhotoDeletedEventListener extends ExchangeListener {
    private CommentApplicationService commentApplicationService;
    private MongoPhotoRepository mongoPhotoRepository;
    private MongoAlbumRepository mongoAlbumRepository;

    public PhotoDeletedEventListener(
            CommentApplicationService commentApplicationService,
            MongoPhotoRepository mongoPhotoRepository,
            MongoAlbumRepository mongoAlbumRepository) {
        this.commentApplicationService = commentApplicationService;
        this.mongoPhotoRepository = mongoPhotoRepository;
        this.mongoAlbumRepository = mongoAlbumRepository;
    }

    @Override
    protected String exchangeName() {
        return Exchanges.DEFAULT_EXCHANGE_NAME;
    }

    @Override
    protected void filteredDispatch(String aType, String aTextMessage) {
        NotificationReader reader = new NotificationReader(aTextMessage);
        String photoId = reader.eventStringValue("photoId.identity");

        if (StringUtils.isNotBlank(photoId)) {
            commentApplicationService().delete(
                    new DeleteCommentsCommand(photoId));

            mongoAlbumRepository().removePhoto(photoId);
            mongoPhotoRepository().removeOne(photoId);
        }
    }

    @Override
    protected String[] listensTo() {
        return new String[]{"com.sumer.psychology.photo.domain.model.PhotoDeletedEvent"};
    }

    private CommentApplicationService commentApplicationService() {
        return commentApplicationService;
    }

    private MongoPhotoRepository mongoPhotoRepository() {
        return mongoPhotoRepository;
    }

    public MongoAlbumRepository mongoAlbumRepository() {
        return mongoAlbumRepository;
    }
}
